package cn.liumouren.util;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;


public class POIUtils {
    private final static String xls = "xls";
    private final static String xlsx = "xlsx";
    private final static String DATE_FORMAT = "yyyy/MM/dd";
//    private static int SKIP_COUNT = 0;   //跳过的行数

    public static List<String[]> readExcel(MultipartFile file) throws IOException {
        return readExcel(file, 0);
    }

    /**
     * 读入excel文件，解析后返回
     *
     * @param file
     * @param skipCount 跳过的行数, 即为表头之上的行数
     * @return
     * @throws IOException
     */
    public static List<String[]> readExcel(MultipartFile file, int skipCount) throws IOException {
        //检查文件
        checkFile(file);
        //获得Workbook工作薄对象
        Workbook workbook = getWorkBook(file);
        //创建返回对象，把每行中的值作为一个数组，所有行作为一个集合返回
        List<String[]> list = new ArrayList<String[]>();
        if (workbook != null) {
            for (int sheetNum = 0; sheetNum < workbook.getNumberOfSheets(); sheetNum++) {
                //获得当前sheet工作表
                Sheet sheet = workbook.getSheetAt(sheetNum);
                if (sheet == null) {
                    continue;
                }
                //获得当前sheet的开始行
                int firstRowNum = sheet.getFirstRowNum();
                //获得当前sheet的结束行
                int lastRowNum = sheet.getLastRowNum();
                //循环除了第一行的所有行
                for (int rowNum = firstRowNum + skipCount; rowNum <= lastRowNum; rowNum++) {
                    //获得当前行
                    Row row = sheet.getRow(rowNum);
                    if (row == null) {
                        continue;
                    }
                    //获得当前行的开始列
                    int firstCellNum = row.getFirstCellNum();
                    //获得当前行的列数
                    int lastCellNum = row.getPhysicalNumberOfCells();
                    String[] cells = new String[row.getPhysicalNumberOfCells()];
                    //循环当前行
                    for (int cellNum = firstCellNum; cellNum < lastCellNum; cellNum++) {
                        Cell cell = row.getCell(cellNum);
                        cells[cellNum] = getCellValue(cell);
                    }
                    list.add(cells);
                }
            }
            workbook.close();
        }
        return list;
    }

    //校验文件是否合法
    public static void checkFile(MultipartFile file) throws IOException {
        //判断文件是否存在
        if (null == file) {
            throw new FileNotFoundException("文件不存在！");
        }
        //获得文件名
        String fileName = file.getOriginalFilename();
        //判断文件是否是excel文件
        if (!fileName.endsWith(xls) && !fileName.endsWith(xlsx)) {
            throw new IOException(fileName + "不是excel文件");
        }
    }

    public static Workbook getWorkBook(MultipartFile file) {
        //获得文件名
        String fileName = file.getOriginalFilename();
        //创建Workbook工作薄对象，表示整个excel
        Workbook workbook = null;
        try {
            //获取excel文件的io流
            InputStream is = file.getInputStream();
            //根据文件后缀名不同(xls和xlsx)获得不同的Workbook实现类对象
            if (fileName.endsWith(xls)) {
                //2003
                workbook = new HSSFWorkbook(is);
            } else if (fileName.endsWith(xlsx)) {
                //2007
                workbook = new XSSFWorkbook(is);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return workbook;
    }

    public static String getCellValue(Cell cell) {
        String cellValue = "";
        if (cell == null) {
            return cellValue;
        }
        //如果当前单元格内容为日期类型，需要特殊处理
        String dataFormatString = cell.getCellStyle().getDataFormatString();
        if (dataFormatString.equals("m/d/yy")) {
            cellValue = new SimpleDateFormat(DATE_FORMAT).format(cell.getDateCellValue());
            return cellValue;//"2019/10/10"
        }
        //把数字当成String来读，避免出现1读成1.0的情况
        if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) {
            cell.setCellType(Cell.CELL_TYPE_STRING);
        }
        //判断数据的类型
        switch (cell.getCellType()) {
            case Cell.CELL_TYPE_NUMERIC: //数字
                cellValue = String.valueOf(cell.getNumericCellValue());
                break;
            case Cell.CELL_TYPE_STRING: //字符串
                cellValue = String.valueOf(cell.getStringCellValue());
                break;
            case Cell.CELL_TYPE_BOOLEAN: //Boolean
                cellValue = String.valueOf(cell.getBooleanCellValue());
                break;
            case Cell.CELL_TYPE_FORMULA: //公式
                cellValue = String.valueOf(cell.getCellFormula());
                break;
            case Cell.CELL_TYPE_BLANK: //空值
                cellValue = "";
                break;
            case Cell.CELL_TYPE_ERROR: //故障
                cellValue = "非法字符";
                break;
            default:
                cellValue = "未知类型";
                break;
        }
        return cellValue;
    }

    /**
     * @param data 写入的数据
     * @param head 表头数据
     * @return
     */
    public static XSSFWorkbook writeToExcel(List<String[]> data, String[] head) {
        XSSFWorkbook excelSheets = new XSSFWorkbook();
        XSSFSheet sheet = excelSheets.createSheet();
        //创建表头
        XSSFRow row = sheet.createRow(0);
        XSSFCell cell;
        for (int i = 0; i < head.length; i++) {
            cell = row.createCell(i);
            cell.setCellValue(head[i]);
        }
        //填充数据
        for (int i = 0; i < data.size(); i++) {
            row = sheet.createRow(i + 1);
            for (int j = 0; j < head.length; j++) {
                cell = row.createCell(j);
                cell.setCellValue(data.get(i)[j]);
            }
        }
        return excelSheets;
    }


    /**
     * @param data     写入的数据
     * @param head     表头数据
     * @param title    标题
     * @param titleNum 标题所占行数
     * @return
     */
    public static XSSFWorkbook writeToExcel(List<String[]> data, String[] head, String title, int titleNum) {
        int rowNum = 0; //row所在行数
        XSSFWorkbook excelSheets = new XSSFWorkbook();
        XSSFCellStyle cellStyle = excelSheets.createCellStyle();
        cellStyle.setAlignment(HorizontalAlignment.CENTER);
        cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        XSSFSheet sheet = excelSheets.createSheet();

        //创建title所占的行数和列数
        XSSFRow row;
        XSSFCell cell;
        for (int i = 0; i < titleNum; i++) {
            row = sheet.createRow(i);
            rowNum++;
            for (int j = 0; j < head.length; j++) {
                row.createCell(j);
            }
        }

        //合并title所占的单元格
        sheet.addMergedRegion(new CellRangeAddress(0, titleNum - 1, 0, head.length - 1));
        row = sheet.getRow(0);
        cell = row.getCell(0);
        cell.setCellValue(title);
        cell.setCellStyle(cellStyle);

        //写入head
        row = sheet.createRow(rowNum);
        rowNum++;
        for (int i = 0; i < head.length; i++) {
            cell = row.createCell(i);
            cell.setCellValue(head[i]);
            cell.setCellStyle(cellStyle);  //设置居中
        }

        //填充数据
        for (String[] datum : data) {
            row = sheet.createRow(rowNum);
            rowNum++;
            for (int j = 0; j < head.length; j++) {
                cell = row.createCell(j);
                cell.setCellValue(datum[j]);
                cell.setCellStyle(cellStyle);
            }
        }

        return excelSheets;
    }

    public static void download(HttpServletResponse response, XSSFWorkbook excelSheets, String filename) throws IOException {
        BufferedOutputStream bufferedOutputStream = null;
        try {
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8"));
            bufferedOutputStream = new BufferedOutputStream(response.getOutputStream());
            excelSheets.write(bufferedOutputStream);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            excelSheets.close();
            if (bufferedOutputStream != null) {
                bufferedOutputStream.close();
            }
        }
    }
}
